<template>
  <div>
    <el-row :gutter="20">
      <el-col :sm="2" class="hidden-xs-only" style="opacity:0;">左侧占位</el-col>
      <el-col :sm="20">
        <el-card style="background-color: rgba(255, 255, 255,1)" class="first-card">
          <div slot="header" class="total blog-info">
            <div v-if="blog.contentType === '1'" class="user-info">
              <i class="el-icon-user"></i>
              <span class="header">  {{ blog.studentName }}</span>
            </div>
            <div v-if="blog.contentType === '2'" class="user-info">
              <i class="el-icon-document"></i>
              <span class="header">课堂记录</span>
            </div>
            <div class="blog-date" style="margin-left: 20px">
              <i class="el-icon-date"></i>
              <span>  {{ blog.createTime }}</span>
            </div>
            <div class="blog-views" style="margin-left: 20px">
              <i class="el-icon-view"></i>
              <span>  {{ blog.views }}</span>
            </div>
            <div class="blog-views" style="margin-left: 20px">
              创建人
              <span>  {{ blog.createBy }}</span>
            </div>
          </div>
          <h2 class="blog-title header">{{ blog.title }}
            <el-tag size="mini" v-for="tag in blog.types" :key="tag.typeId" type="info">{{ tag.typeName }}</el-tag>
          </h2>

          <div @click="handleVHtmlLinkClick"  v-html="blog.content"></div>

          <div class="tags" style="display: flex">
            <div class="tag-item" v-for="tag in blog.tags" :key="tag.tagId">
              <div class="sjx-outer">
                <div class="sjx-inner"></div>
              </div>
              <div class="tag">
                {{ tag.tagName }}
              </div>
            </div>
          </div>

          <el-table :data="blog.blogFilesNew" :border="true" style="width: 99.99%;margin-top: 30px">
            <el-table-column align="center" min-width="30%" prop="remark" label="附件">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="6">
                    <div class="blogFilesInfoName">名称：</div>
                  </el-col>
                  <el-col :span="18">
                    <el-input v-model="scope.row.fileOriginName" disabled/>
                  </el-col>
                </el-row>
                <el-row style="margin-top: 4px;">
                  <el-col :span="6">
                    <div class="blogFilesInfoName">大小：</div>
                  </el-col>
                  <el-col :span="18">
                    <el-input v-model="scope.row.fileSize" disabled/>
                  </el-col>
                </el-row>
                <el-row style="margin-top: 4px;">
                  <el-col :span="6">
                    <div class="blogFilesInfoName">类型：</div>
                  </el-col>
                  <el-col :span="18">
                    <el-input v-model="scope.row.fileSuffix" disabled/>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="50%" prop="remark" label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" type="textarea" :rows="6" size="small" disabled/>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="20%" label="操作">
              <template slot-scope="scope">
                <el-button size="mini" plain @click="handleDownload(scope.row)">下载</el-button>
                <el-button size="mini" plain @click="handlePreview(scope.row)">预览</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-divider content-position="right">文章到此结束</el-divider>
          <el-card shadow="never" class="comments">
            <div class="header" style="padding-bottom: 10px;">
              评论
            </div>
            <comment></comment>
          </el-card>
        </el-card>
      </el-col>
      <el-col :sm="2" class="hidden-xs-only" style="opacity:0;">右侧占位</el-col>
      <!-- 设置底部距离的 -->
      <el-backtop :bottom="60">
        <div
          style="
            height: 50px;
            width: 50px;
            background-color: rgba(240,239,241,1);
            box-shadow: 0 0 6px rgba(0,0,0, .12);
            text-align: center;
            line-height: 40px;
            border-radius:2px;
            color: #1989fa;
          "
        >
          <svg-icon icon-class="top"/>
        </div>
      </el-backtop>
    </el-row>

    <CustomImagePreview
      :isShow.sync="showViewer"
      :image-list="imageList"
    />
  </div>
</template>

<script>
//使用prism.js代码高亮
import '@/views/cms/plugins/prism.js'
import '@/views/cms/plugins/prism.css'
import comment from '../../comment/components/Ipcomment.vue'
import {
  getBlogDetail,
  addBlogViews
} from '@/api/cms/blog'
import { mapState } from 'vuex'

import CustomImagePreview from '@/components/pic/CustomImagePreview.vue';


export default {
  components: {
    comment,
    CustomImagePreview // 注册预览组件
  },
  data() {
    return {
      blog: {},
      showViewer: false, // 是否显示预览组件
      previewIndex: 0, // 当前预览图片的索引
      imageUrl: '',
      imageList: [],
      commentForm: {
        content: ''
      }
    }
  },
  watch: {
    '$route'(to, from) {
      this.$router.go(0)
    }
  },
  created() {
    this.getBlogInformation()
  },
  mounted() {
  },
  computed: {
    ...mapState([
      'userInfo',
      'administrator'
    ])
  },
  methods: {
    // 获取成长记录详情信息
    async getBlogInformation() {
      // 增加阅读量
      addBlogViews(this.$route.query.id)
      getBlogDetail(this.$route.query.id).then(response => {
        const { data: res } = response
        // console.log(res)
        this.blog = response.data
        this.blog.blogFilesNew = []
        //添加对学生的评论
        if (res.contentType === '2'){
          const comments = JSON.parse(res.contentMarkdown)
          // let picJSON = Array.from(res.blogPic);
          // let picJSON = res.blogPic.split(/(}),/);
          let pic = res.blogPic
          let picJSON = res.blogPic.replaceAll('},',"}&");
          if (pic !== undefined && pic !== null && pic !== '') {
            picJSON = picJSON.split('&')
          }
          // console.log(picJSON)
          let comment = '<div class="span_border" style="min-width: 500px;font-weight: bold">' + this.blog.content + '</div>'
          Object.keys(comments).forEach(key => {
            //数组中查找
            let studentArray = []

            //评论样式
            const studentComment = '<p style="font-weight: bold">' +
              '<span class="span_border" style="' +
              'margin-right: 20px;display: inline-block;min-width: 80px">' + key  + ':' + '</span>' +
              '<span class="span_border" style="' +
              'display: inline-block;min-width: 200px;">'  + comments[key] +  '</span>'

            if (pic !== undefined && pic !== null && pic !== '') {
              studentArray = picJSON.filter(item => {
                let json = JSON.parse(item);
                return json['studentId'] === key
              })
            }
            // console.log(studentArray)
            let picURL = ''
            let picURL2 = ''
            if(studentArray.length === 1){
              picURL = JSON.parse(studentArray[0])['pic0']
              const dataUrl = 'http://101.43.194.26:81/prod-api' + picURL
              comment += studentComment +
                '<span class="span_border" style="color: #00afff;margin-left: 10px;display: inline-block;">' +
                // '<a target="_blank" href=" ' + 'http://101.43.194.26:81/prod-api' + picURL + ' ">图片1</a>' +
                '<a data-url=" ' + dataUrl + ' " href="javascript:;">图片1</a></span>' +
                '</span>' +
                '</p>'
            }
            else if (studentArray.length >= 2){
              picURL = JSON.parse(studentArray[0])['pic0']
              picURL2 = JSON.parse(studentArray[1])['pic1']
              const dataUrl = 'http://101.43.194.26:81/prod-api' + picURL
              const dataUrl2 = 'http://101.43.194.26:81/prod-api' + picURL2
              comment += studentComment +
                '<span class="span_border" style="color: #00afff;margin-left: 10px;display: inline-block;">' +
                // '<a target="_blank" href=" ' + 'http://101.43.194.26:81/prod-api' + picURL + ' ">图片1</a></span>' +
                '<a data-url=" ' + dataUrl + ' " href="javascript:;">图片1</a></span>' +
                '<span class="span_border" style="color: #00afff;margin-left: 10px;display: inline-block;">' +
                // '<a target="_blank" href=" ' + 'http://101.43.194.26:81/prod-api' + picURL2 + ' ">图片2</a></span>' +
                '<a data-url=" ' + dataUrl2 + ' " href="javascript:;">图片2</a></span>' +
                '</p>'
            }
            else {
              comment += studentComment + '</p>'
            }
          })
          this.blog.content =  comment
        }
        if (response.data.blogFiles !== null) {
          this.blog.blogFilesNew = JSON.parse(response.data.blogFiles)
        }
      })
    },
    handleVHtmlLinkClick(e) {
      // 1. 判断点击的目标是否为 <a> 标签（或包含在a标签内）
      const targetA = e.target.closest('a');
      // console.log(targetA);
      // closest('a')：找到最近的祖先a标签（解决a标签内有子元素的情况，如<a><span>链接</span></a>）

      if (targetA) {
        // 2. 阻止a标签默认行为（如跳转）
        // e.preventDefault();

        // 3. 获取a标签的自定义属性（如data-id）
        const linkId = targetA.dataset.url;
        // console.log('点击了v-html内的a标签，url:', linkId);

        // 4. 执行自定义逻辑（如跳转、请求等）
        this.handleLocalPreview(linkId);

        // 阻止事件冒泡到父元素
        e.stopPropagation();
      }
    },
    // 处理a标签点击，打开预览
    handleLocalPreview(url) {
      if (this.showViewer) return; // 已打开则不再重复操作
      // console.log(index)
      this.imageList = [url]
      this.showViewer = true; // 显示预览组件
      // setTimeout(()=> {
      //   this.showViewer = false;
      // },5000)
    },
    // 文件下载处理
    handleDownload(row) {
      var name = row.fileOriginName
      var url = row.filePath
      var suffix = url.substring(url.lastIndexOf('.'), url.length)
      const a = document.createElement('a')
      a.setAttribute('download', name)
      a.setAttribute('target', '_blank')
      a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
      a.click()
    },
    // 文件预览处理
    async handlePreview(row) {
      var name = row.fileOriginName
      var filePath = row.filePath
      var url = process.env.VUE_APP_BASE_API + filePath
      const response = await fetch(url)
      if (response.status === 200) {
        const blob = await response.blob()
        var objectURL = window.URL.createObjectURL(blob)
        var openUrl = window.location.origin + '/fileViewer/index.html' + '?name=' + name + '&url=' + objectURL
        window.open(openUrl)
      } else {
        this.$message.error('文件不存在！')
      }
    }
  }

}
</script>

<style scoped>

.first-card {
  border-radius: 10px 10px 10px 10px;
  position: relative;
  padding-bottom: 10px;
  /*text-align: center;*/
  font: 300 1em/1.8 PingFang SC, Lantinghei SC, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif;
}

.tags {
  align-items: center;
  margin-left: 50px;
  margin-top: 20px;
}

.tag-item {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-left: 10px;
  margin-bottom: 20px;
}

.tag {
  padding-left: 10px;
  padding-right: 10px;
  border-radius: 5px;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  color: #409eff;
  display: flex;
}

.sjx-outer {
  width: 0;
  height: 0;
  border-top: 7px solid transparent;
  border-bottom: 7px solid transparent;
  border-right: 7px solid #409eff;
  position: relative;
}

.sjx-inner {
  border-top: 7px solid transparent;
  border-bottom: 7px solid transparent;
  border-right: 7px solid #ecf5ff;
  top: -7px;
  left: 1px;
  position: absolute;
}

.comments {
  margin-top: 50px;
  box-shadow: 0 1px 2px 0 rgb(34 36 38 / 15%);
  border: 1px solid rgba(34, 36, 38, .15);
  border-top: 2px solid #409EFF;
  text-align: left;
}

.blog-title {
  text-align: center;
}

.blog-info {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.blog-date {
  margin-right: 5px;
  float: right;
}

.blog-views {
  margin-right: 5px;
  float: right;
}

.user-info {
  justify-content: space-around;
  align-items: center;
  margin-right: 15px;
  float: left;
}

.header {
  text-decoration: none;
  color: #3a8ee6;
  font-weight: bold;
}

@media only screen and (max-width: 480px) {
  h2 {
    font-weight: normal;
  }

  code, pre {
    font-size: 13px !important;
  }
}

.blogFilesInfoName {
  text-align: center;
  padding-top: 5px;
}

 /*内容的边框*/
::v-deep .span_border{
  border:1px solid #dcdfe6;
  border-radius:8px;
  padding:10px;
  background-color: white;
}

/* 确保关闭按钮可点击 */
::v-deep .el-image-viewer__close {
  z-index: 3001; /* 高于模态框层级 */
  pointer-events: auto;
  opacity: 1;
}

/* 修复：确保可点击 */
::v-deep .el-image-viewer__mask {
  display: none; /* 完全移除遮罩层的显示 */
  pointer-events: auto; /* 允许点击事件 */
}



</style>

